<?php
/**
 * Created by PhpStorm.
 * User: william
 * Date: 16-8-31
 * Time: 下午2:44
 */
namespace V1;
class C_Product extends \ResourceClass {
    public $isActive = true;
    public $remark = '获取产品详情';

    public function get(array $req, array $post, &$result)
    {
        if (!isset($req['uid'])) {
            return 'require user id ';
        }
        if (!isset($req['userType'])) {
            return 'require user type';
        }
        if (!isset($req['k']) || !isset($req['t'])) {
            return 'data error';
        }
        if (!isset($req['id'])) {
            return 'require product id';
        }

        if (!isset($req['enterpriseId'])) {
            return 'require enterprise id';
        }
        if (\Biz\UserHandler::checkAuth($req['userType'], $req['uid'], $req['enterpriseId'], $req['id'] . $req['t'], $req['k']) == false) {
             return 'data illegal';
        }

        if (!isset($req['channelId'])) {
            return 'require channel id';
        }
        $customer_info = \Biz\EnterpriseCustomerHandler::getEnterpriseCustomerById($req['enterpriseId'], $req['uid']);
        $customer_channel_id = $customer_info->getChannelId();
        $customer_enterprise_id = $customer_info->getEnterpriseId();

        if ($customer_channel_id != $req['channelId']) {    //验证用户渠道
            return '渠道商品获取失败!';
        }
        if ($customer_enterprise_id != $req['enterpriseId']) {//验证用户企业
            return '企业用户获取失败!';
        }
        $product_handler = new \Biz\ProductHandler();
        $product_cls = $product_handler->getProductById($req['id']);
        // 获取当前渠道信息
        $channel_cls = \Biz\ChannelHandler::getChannelById($req['channelId']);
        $discount = $channel_cls->getDiscount();
        /**
         * @var $product_cls \Cls\Product\Product
         */
        $product_cls_temp = new \stdClass();
        $product_cls_temp->id = $product_cls->getId();
        $product_cls_temp->enterprise_id = $product_cls->getEnterpriseId();
        $product_cls_temp->brand_id = $product_cls->getBrandId();
        $product_cls_temp->name = $product_cls->getName();
        $product_cls_temp->icon_url = $product_cls->dealIconUrl();
        $product_cls_temp->repertory_warning = $product_cls->getStockWarning();
        $product_cls_temp->individual_packing = $product_cls->getSellUnitString(); // 老版本
        $product_cls_temp->mass_packing = $product_cls->getSellUnitString();  // 老版本
        $product_cls_temp->sell_unit_string = $product_cls->getSellUnitString();
        $product_cls_temp->remark = $product_cls->getDescription();
        $product_cls_temp->insert_time = $product_cls->getCreateTime();
        $product_cls_temp->is_del = $product_cls->getDelStatus();
        /**
         * 增加富文本信息
         */
        if ($_SERVER['HTTP_HOST'] == 'rest.test.freshqiao.com') {
            $product_cls_temp->rich_text_url = 'http://enterprise.test.freshqiao.com/product/detail-description-rich?id='.$product_cls_temp->id;
        } else if ($_SERVER['HTTP_HOST'] == 'rest.freshqiao.com') {
            $product_cls_temp->rich_text_url = 'http://enterprise.freshqiao.com/product/detail-description-rich?id='.$product_cls_temp->id;
        } else {
            $product_cls_temp->rich_text_url = '';
        }
        $brand_cls = $product_cls->getBrandInfo();
        if ($brand_cls instanceof \Cls\Brand\Brand) {
            $brand_name = $brand_cls->getName();
        } else {
            $brand_name = '未知分类名称';
        }
        $product_cls_temp->brandname = $brand_name;
        $channel_list = $product_cls->getChannelProduct();
        if (empty($channel_list)) {
            $result = array();
            return '您所在渠道没有此商品，或商品已下架';
        }
        $product_cls_temp->channel_price = $channel_list[$customer_channel_id]->getPriceRange();
        $product_cls_temp->collect_stock = $product_cls->getRepertoryTotal();
        $product_cls_temp->stock_warning = $product_cls->judgeStockWaring();
        $sku_list = $product_cls->getSkuList();
        $product_cls_temp->sku_info = array();

        $product_cls_temp->scroller_imgs = array();
        $product_cls_temp->detail_imgs = array();
        $image_list = $product_cls->getAllImageList();
        foreach ($image_list as $image_list => $image_cls) {
            if ($image_cls->getType() == \Cls\Product\Image::IMAGE_TYPE_PRODUCT) {
                $product_cls_temp->scroller_imgs [] = 'http://image.freshqiao.com/' . $image_cls->getUrl();
            } elseif ($image_cls->getType() == \Cls\Product\Image::IMAGE_TYPE_DESC) {
                $product_cls_temp->detail_imgs [] = 'http://image.freshqiao.com/' . $image_cls->getUrl();
            }
        }
        if (!empty($sku_list)) {
            /**
             * @var $sku_cls \Cls\Product\Sku
             */
            foreach ($sku_list as $sku_cls) {
                $sku_temp = new \stdClass();
                $sku_temp->id = $sku_cls->getId();
                $sku_temp->product_id = $sku_cls->getProductId();
                $sku_temp->attr = $sku_cls->dealAttr();
                $sku_temp->code = $sku_cls->getCode();
                $sku_temp->sellprice = $sku_cls->getChannelSellingPrice($discount);
                $sku_temp->cost = $sku_cls->getCost();
                $sku_temp->imgurl = $sku_cls->getImageUrl();
                $sku_temp->stock = $sku_cls->getStock();
                $sku_temp->insert_time = $sku_cls->getCreateTime();
                $sku_temp->update_time = $sku_cls->getUpdateTime();
                $product_cls_temp->sku_info [] = $sku_temp;
            }
        }

        $result = $product_cls_temp;
        $market_product_discount = array();
        if ($result) {
            $collection_handler = new \Biz\CustomerCollectionHandler();
            $collection_status = $collection_handler::getCollectionState($customer_enterprise_id, $req['id'], $customer_channel_id);
            $collection_status = $collection_status ? $collection_status->getIsDel() : '0';
            $result->collection_status = (string)$collection_status;
            /*
             *  促销活动信息
             *  ①筛选该企业下的所有有效活动
             *  ②在活动中筛选出用户所在渠道的活动，即活动的渠道为所有活动或者参与渠道中包含该渠道即可
             *  ③把满足条件的活动参与的产品与查询出的产品对应起来
             *  ④返回活动信息
             */
            $market_biz = new \Biz\MarketHandler();
            $tabulation = new \Cls\Tabulation();
            $tabulation->setLimit(99999);
            $tabulation->setWhere('enterprise_id', $req['enterpriseId']);
            $tabulation->setWhere('end_time','>',date('Y-m-d H:i:s',time()));
            $market_biz->getListByEnterpriseId($tabulation);
            if ($tabulation->getSuccessStatus()) {
                $market_list = $tabulation->getData();
                //营销活动的渠道信息
                $market_biz->completeChannelListByMarketList($market_list);
                //完善营销活动中的商品信息
                $market_biz->completeProductListByMarketProductList($market_list);
                /**
                 * @var $market_cls \Cls\Market\Market
                 */

                foreach ($market_list as $market_cls) {
                    //如果活动参与的渠道类型是所有渠道或者当前用户所在的渠道在参与活动的渠道中
                    if ($market_cls->getChannelType() == \Cls\Market\Market::CHANNEL_ALL || $market_cls->judgeInChannel($req['channelId'])) {
                        //获取该活动参与的所有产品
                        $market_product_list = $market_cls->getProductList();
                        $product_ids = array();
                        foreach ($market_product_list as $market_product_cls) {
                            $product_ids[] = $market_product_cls->getProductId();
                        }
                        //如果参与活动产品类型为所有产品或者该产品在参与的活动中
                        $result->activity_info = isset($result->activity_info) ? $result->activity_info : array();
                        if ($market_cls->getProductType() == \Cls\Market\Market::PRODUCT_ALL || in_array($result->id, $product_ids)) {
                            $market_product_discount = $market_cls->getDicount();
                            $market_cls_temp = new \stdClass();
                            $market_cls_temp->id = $market_cls->getId();
                            $market_cls_temp->title = $market_cls->getTitle();
                            $market_cls_temp->type = $market_cls->getType();
                            $market_cls_temp->condition = $market_cls->getCondition();
                            $market_cls_temp->discount = $market_cls->getDicount();
                            $market_cls_temp->rewards = $market_cls->getRewards();
                            $market_cls_temp->product_type = $market_cls->getProductType();
                            $market_cls_temp->channel_type = $market_cls->getChannelType();
                            $market_cls_temp->start_time = $market_cls->getStartTime();
                            $market_cls_temp->end_time = $market_cls->getEndTime();
                            $market_cls_temp->status = $market_cls->getStatus();
                            $market_cls_temp->enterprise_id = $market_cls->getEnterpriseId();
                            $market_cls_temp->unit = $market_cls->getUnit();
                            $market_cls_temp->create_time = $market_cls->getCreateAt();
                            $market_cls_temp->edit_time = $market_cls->getUpdateAt();
                            $market_cls_temp->update_time = $market_cls->getUpdateAt();
                            $market_cls_temp->is_del = (string)$market_cls->getIsDel();
                            array_push($result->activity_info, $market_cls_temp);
                        }
                    }
                }
                //计算折扣  按折扣活动的更新时间为键
                if ((isset($result->activity_info)&&!empty($result->activity_info))) {
                    $new_activity = array();
                    foreach ($result->activity_info as $key => $activity) {
                        if ($activity->type == \Cls\Market\Market::TYPE_LOW_PRICE) { //只有活动类型为低价促时，才重新计算价格
                            $time = strtotime($activity->update_time);
                            $new_activity[$time] = $activity;
                            //因为后面需要重新筛选折扣活动，所以需要把原先的折扣活动删除
                            unset($result->activity_info[$key]);
                        }
                    }
                    $new_activity = isset($new_activity) ? $new_activity : array();
                    krsort($new_activity);//把最新的折扣活动放前面
                    $sort_activity = current($new_activity);//取出最终满足的活动
                    if(!empty($sort_activity)) {
                        foreach($result->sku_info as $ke => $sku_cls){
                            $result->sku_info[$ke]->sellprice = round($sku_cls->sellprice*$sort_activity->discount,2);
                        }
                        array_push($result->activity_info,$sort_activity);
                    }
                }else{
                    $result->activity_info = array();
                }
                $activity_info = array_merge($result->activity_info);
                $result->activity_info = $activity_info;
            } else {
                $result = array();
                return '您所在渠道没有此商品，或商品已下架';
            }
        }
    }
}



